#include <stdint.h>
#include "lcd.h"
#include "board.h"

// 向LCD1602写命令，E为高脉冲
void lcd_write_cmd(uint8_t cmd)
{
    LCD_E = 0;
    LCD_RS = 0;
    LCD_RW = 0;
    LCD_DATA = cmd;
    __asm__ ("nop");
    LCD_E = 1;
    __asm__ ("nop");
    LCD_E = 0;
    delay_ms(1);
}

// 向LCD1602写数据，E为高脉冲
void lcd_write_data(uint8_t data)
{
    LCD_E = 0;
    LCD_RS = 1;
    LCD_RW = 0;
    LCD_DATA = data;
    __asm__ ("nop");
    LCD_E = 1;
    __asm__ ("nop");
    LCD_E = 0;
    delay_ms(1);
}

// LCD忙状态判断
void lcd_wait()
{
    uint8_t state;
    LCD_DATA = 0xff;
    // 读取LCD的状态进行判断
    LCD_RS = 0;
    LCD_RW = 1;
    do
    {
        LCD_E = 1;
        state = LCD_DATA;
        LCD_E = 0;
    } while (state & 0x80);
}

// LCD1602初始化
void lcd_init()
{
    lcd_write_cmd(0x38); // 显示为2x16格式
    lcd_write_cmd(0x38); // 显示为2x16格式
    lcd_write_cmd(0x0C); // 不显示光标
    lcd_write_cmd(0x06); // 读入后AC（指针）加1，向右写
    lcd_write_cmd(0x01); // 清除屏幕
}

void lcd_write_str(const char *s) {
    uint8_t i = 0;
    char c;
    while (c=s[i], c) {
        lcd_write_data(c);
        ++i;
    }
}
